#include <deque>
#include <map>
#include <algorithm>
#include "ITimeEvent.h"

class ITimeEvent;
struct CTimeEventInfo
{
	ITimeEvent* m_pItemEvent;
	int m_nTimeEventID;
};
class CTimer
{
public:
	CTimer():m_TimeEventID(0),m_NextTick(-1)
	{
		m_nTime = GetTickCount() ;
	};
	~CTimer(){};
	int AddEvent(ITimeEvent* pEvent,long nTime)
	{
		nTime += m_nTime;
		m_listTime.push_back(nTime);
		push_heap(m_listTime.begin(),m_listTime.end(),greater<long>());
		m_NextTick = m_listTime.front();
		m_TimeEventID++;
		CTimeEventInfo* pInfo = new CTimeEventInfo();
		pInfo->m_pItemEvent = pEvent;
		pInfo->m_nTimeEventID = m_TimeEventID;
		m_mapEvent[nTime] = pInfo;
		return m_TimeEventID;
	}
	void heartBeat()
	{
		m_nTime = GetTickCount() ;
		while(1)
		{
			if (m_NextTick !=-1 && m_nTime > m_NextTick)
			{
				if(m_mapEvent[m_NextTick]->m_pItemEvent)
					m_mapEvent[m_NextTick]->m_pItemEvent->OnSignal(m_mapEvent[m_NextTick]->m_nTimeEventID);
				m_mapEvent.erase(m_NextTick);
				pop_heap(m_listTime.begin(),m_listTime.end(),greater<long>());
				m_listTime.pop_back();
				if(!m_listTime.empty())
					m_NextTick = m_listTime.front();
				else
					m_NextTick = -1;
			}
			else
			{
				break;
			}
		}
		
	}
private:
	long m_nTime;
	int m_TimeEventID;
	std::deque<long> m_listTime;
	std::map<long,CTimeEventInfo*> m_mapEvent;
	long m_NextTick;
};